<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use app\admin\model\Litestorespec as SpecModel;
use app\admin\model\Litestorespecvalue as SpecValueModel;
use app\common\model\Category as CategoryModel;
use fast\Tree;
use think\Db;

/**
 * 
 *
 * @icon fa fa-circle-o
 */
class LitestoreGoods extends Backend
{
    
    /**
     * LitestoreGoods模型对象
     * @var \app\admin\model\LitestoreGoods
     */
    private $SpecModel;
    protected $model = null;
    protected $categorylist = [];
    private $SpecValueModel;
    protected $searchFields = 'goods_name';
    protected $multiFields="good_status";


    public function _initialize()
    {
        parent::_initialize();
        $this->catemodel = model('app\common\model\Category');

        $tree = Tree::instance();
        $tree->init(collection($this->catemodel->order('weigh desc,id desc')->select())->toArray(), 'pid');
        $this->categorylist = $tree->getTreeList($tree->getTreeArray(0), 'name');
        $categorydata = [0 => ['type' => 'all', 'name' => __('None')]];
        foreach ($this->categorylist as $k => $v) {
            $categorydata[$v['id']] = $v;
        }
        $typeList = CategoryModel::getTypeList();
        $this->view->assign("typeList", $typeList);
        $this->view->assign("parentList", $categorydata);
        $this->assignconfig('typeList', $typeList);

        $this->SpecModel = new SpecModel;
        $this->SpecValueModel = new SpecValueModel;
        $this->model = new \app\admin\model\LitestoreGoods;

        $this->view->assign("flagList", $this->catemodel->getFlagList());
        $this->assignconfig('flagList', $this->catemodel->getFlagList());
        
        $this->view->assign("ShowList", $this->model->getShowList());//商品展示位置（可多选）
        

        $this->view->assign("specTypeList", $this->model->getSpecTypeList());
        $this->view->assign("deductStockTypeList", $this->model->getDeductStockTypeList());

        $this->view->assign("spec_attr", '');
        $this->view->assign("spec_list", '');

    }
        /**
     * 判断当前的商品是否已经有空闲时间列表
     */
    public function checkFreetime($goods_id){
        $list = Db::name('free_time')->where('goods_id',$goods_id)->find();
        if($list){
            return $this->success('', '', [
                'spec_value_id' => (int)$goods_id,
            ]);
        }else{
            return $this->error();
        }
    }

        /**
     * 编辑
     */
    public function edit($ids = NULL)
    {
        $row = $this->model->get($ids, ['specRel', 'spec', 'spec_rel.spec']);
        // halt($row->toArray());
        if (!$row)
            $this->error(__('No Results were found'));
            $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }

        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");

            $row_array = $row->toArray();
            $pass_spec_attr_num = count($row_array['spec']);
            // halt($pass_spec_attr_num);
            // halt($row_array);

            $spec_a = $this->request->post("spec/a");
            $spec_many_params = $this->request->post("spec_many/a");

            // halt($spec_many_params);
            if ($params) {
                try {

                    $result = $row->allowField(true)->save($params);
                    if ($result !== false) {
                        //成功之后 存储商品规格

                        $row->addGoodsSpec($params,$spec_many_params,$spec_a,true);
                        $this->success();
                    } else {
                        $this->error($row->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                } catch (\think\Exception $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        // 多规格信息
        $specData = 'null';
        if ($row['spec_type'] === '20'){
            $specData = json_encode($this->model->getManySpecData($row['spec_rel'], $row['spec']));
        }else{
            $row = $row->toArray();
        }
        $row['specData'] = $specData;
        
        $this->view->assign("row", $row);
        // halt($row->toArray());
        // dump($row['specData']);die;
        return $this->view->fetch();
    }

     /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {

            $params = $this->request->post("row/a");
            // $spec_many_params = $this->request->post("spec_many/a");
            $spec_a = $this->request->post("spec/a");//单规格的清空获取 价格以及库存数量
            //成功之后 存储商品规格
            $spec_many_params = $this->request->post("spec_many/a");
            if ($params) {
                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                try {

                    if($params['spec_type']=='10'){
                        $params['show_money'] = $spec_a['goods_price'];
                        //spec_a用于单规格,将租期和租期价格转为json
                    }
                    $result = $this->model->allowField(true)->save($params);

                    if ($result !== false) {
                        $this->model->addGoodsSpec($params,$spec_many_params,$spec_a);
                       
                        $this->success();
                    } else {
                        $this->error($this->model->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                } catch (\think\Exception $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }

    /**
     * 添加规格值，在第一个的基础上添加
     */
    public function addSpecValue($spec_id, $spec_value)
    {
        // 判断规格值是否存在
        if ($specValueId = $this->SpecValueModel->getSpecValueIdByName($spec_id, $spec_value)) {
            return $this->success('', '', [
                'spec_value_id' => (int)$specValueId,
            ]);
        }
        // 添加规则值
        if ($this->SpecValueModel->add($spec_id, $spec_value))
            return $this->success('', '', [
                'spec_value_id' => (int)$this->SpecValueModel['id'],
            ]);
        return $this->error();
    }


    public function addSpec($spec_name, $spec_value,$goods_id){

        // 判断规格组是否存在
        if (!$specId = $this->SpecModel->getSpecIdByName($spec_name)) {
            // 新增规格组and规则值
            if ($this->SpecModel->add($spec_name)
                && $this->SpecValueModel->add($this->SpecModel['id'], $spec_value))
                //删除此规格的商品的所有平常价格和库存
                if($goods_id !="") {
                    Db::name('free_time')->where('goods_id', $goods_id)->delete();
                }
            return $this->success('', '', [
                'spec_id' => (int)$this->SpecModel['id'],
                'spec_value_id' => (int)$this->SpecValueModel['id'],
            ]);
            return $this->error();
        }
        //return ;
        // 判断规格值是否存在
        if ($specValueId = $this->SpecValueModel->getSpecValueIdByName($specId, $spec_value)) {
            return $this->success('', '', [
                'spec_id' => (int)$specId,
                'spec_value_id' => (int)$specValueId,

            ]);
        }
        // 添加规则值
        if ($this->SpecValueModel->add($specId, $spec_value))
            return $this->success('', '', [
                'spec_id' => (int)$specId,
                'spec_value_id' => (int)$this->SpecValueModel['id'],
            ]);
        return $this->error();
    }
    

}
